import re
import operator

# the_stk = []
# scanner = re.Scanner([
#     (r'[*+/-]',lambda s,t:bin_op(t)),
#     (r'\d+\.\d*',lambda s,t:the_stk.append(float(t))),
#     (r'\d+',lambda s,t:the_stk.append(int(t))),
#     (r'\s+',None)
# ])
#
# def bin_op(tok):
#     op2,op1 = the_stk.pop(),the_stk.pop()
#     if tok == '+':
#         the_stk.append(op1+op2)
#     elif tok == '*':
#         the_stk.append(op1*op2)
#     elif tok == '/':
#         the_stk.append(op1/op2)
#     elif tok == '-':
#         the_stk.append(op1-op2)
#
#
# def main():
#     input_str = input('Enter RPN string: ')
#     tokens,unknow = scanner.scan(input_str)
#     if unknow:
#         print('Unrecognized input:',unknow)
#     else:
#         print('Answer is',the_stk.pop())
#
# main()


# 上述代码可简化如下 ---------------------------------------

the_stk = []
scanner = re.Scanner([
    (r'[+]',lambda s,t:bin_op(operator.add)),
    (r'[*]',lambda s,t:bin_op(operator.mul)),
    (r'[-]',lambda s,t:bin_op(operator.sub)),
    (r'[/]',lambda s,t:bin_op(operator.truediv)),
    (r'\d+\.\d*',lambda s,t:the_stk.append(float(t))),
    (r'\d+',lambda s,t:the_stk.append(int(t))),
    (r'\s+',None)
])

def bin_op(oper):
    op2,op1 = the_stk.pop(),the_stk.pop()
    the_stk.append(oper(op1,op2))


def main():
    input_str = input('Enter RPN string: ')
    tokens,unknow = scanner.scan(input_str)
    if unknow:
        print('Unrecognized input:',unknow)
    else:
        print('Answer is',the_stk.pop())

main()


